#pragma once
#include"common.hpp"
class InitFIFO {
    public:
        InitFIFO() {
            umask(0);
            int n = ::mkfifo(gpipeFile.c_str(), gmode);//创建管道文件 
            if(n == -1){
                std::cerr << "mkfifo error" << std::endl;
                exit(1);
            }
            std::cout << "mkfifo success" << std::endl;
        }
        ~InitFIFO() {
            int n = ::unlink(gpipeFile.c_str());//删除管道文件
            if(n == -1){
                std::cerr << "unlink error" << std::endl;
                exit(1);
            }
            std::cout << "unlink success" << std::endl;
        }
        
};
class Server {
    public:
        Server(): _fd(-1)
        {}
        // bool OpenPipe() {
        //     _fd = ::open(gpipeFile.c_str(), O_RDONLY);//打开管道文件
        //     if(_fd == -1){
        //         std::cerr << "open error" << std::endl;
        //         return false;
        //     }
        //     return true;
        // }
        bool OpenPipeForRead() {
            _fd = OpenPipe(gflagsforread);//打开管道文件
            if(_fd == -1){
                std::cerr << "open error" << std::endl;
                return false;
            }
            return true;
        }
        int ReadPipe(std::string *p_str) {
            char buffer[gbufSize];
            int n = ::read(_fd, buffer, gbufSize-1);
            if(n == -1){
                std::cerr << "read error" << std::endl;
                return -1;
            }
            else{
                buffer[n] = '\0';
                *p_str = buffer;//将读入的数据存入p_str
                return n;
            }
            
        }
        void ClosePipe() {
            GlobalClosePipe(_fd);
        }
        ~Server() {}
    private:
        int _fd;
};